<template>
  <div>
    <ListTab v-model="handleStatus" :tabs="tabList" :show-header="!showMobilePage" is-table @tabClick="handleTabClick" />
    <div class="customer">
      <div :class="{'mobile-table mobile-min-height':showMobilePage}" class="table-list min-fill-page">
        <div v-if="!showMobilePage" style="position:relative;margin-bottom:16px;">
          <FilterInput v-model="filterInput" :filter-list="filterList" :drawer-size="800" show-search-btn class="FilterTool" @handelClick="queryClick" @queryEmpty="queryEmpty" @filterTagStatus="filterTagStatus" />
          <div class="table-top-opeator-bar">
            <!-- <MoreOpeator
              v-if="hasRouteAuth('crm:contract:add')"
              :list="createOpeatorList"
              style="margin-right: 10px"
            >
              <el-button slot="button" class="btn-right-item batch-set" size="small">
                新建<i class="el-icon-plus el-icon--right"/>
              </el-button>
            </MoreOpeator> -->
            <createBtn v-if="hasRouteAuth('crm:contract:add')" @click.native="toCreate"/>
            <el-button type="primary" size="small" class="empty-btn-style" @click="showContractTemplate">合同模板</el-button>
            <MoreOpeator
              ref="btnGroupRef"
              :list="moreOperatorList"
            />
          </div>
        </div>
        <div v-loading="listLoading" style="min-height: 300px">
          <u-table
            v-if="list && list.items.length > 0"
            ref="legalTableRef"
            :data="list.items"
            :row-class-name="tableRowClassName"
            :height="setTableHeight"
            :row-height="rowHeight()"
            :border="true"
            beautify-table
            header-drag-style
            class="fb-table"
            header-cell-class-name="order-data-header-cell"
            element-loading-text="加载中..."
            empty-text="暂无数据"
            fit
            hightlight-current-rowref="tableRef"
            hightlight-current-row
            @select="selectTable"
            @select-all="selectTable"
            @sort-change="sortMethod">
            <u-table-column
              :fixed="selectFixed"
              align="center"
              type="selection"
              width="50"
            />
            <template v-for="(settingItem) in tableSetting">
              <u-table-column
                v-if="settingItem.isShow && legalTableProps[settingItem.fieldName]"
                :key="settingItem.fieldName"
                v-bind="legalTableProps[settingItem.fieldName]"
                :label-class-name="`${settingItem.fieldName === 'flowCode' ? 'diy-cell' : ''}`"
                :class-name="`${settingItem.fieldName === 'flowCode' ? 'diy-cell' : ''}`"
              >
                <template slot-scope="scope" slot="header">
                  <span v-if="settingItem.fieldName === 'flowCode'" class="diyHeader">{{ scope.column.label }}</span>
                  <span v-else>{{ scope.column.label }}</span>
                </template>
                <template slot-scope="scope">
                  <template v-if="settingItem.fieldName === 'flowCode'">
                    <processSn :is-expedited="scope.row.isExpedited">
                      <ToolTip :content="scope.row.flowCode" is-can-click @handelClick="toDetail(scope.row)" />
                    </processSn>
                  </template>
                  <template v-else-if="settingItem.fieldName === 'platform'" slot-scope="scope">
                    <div class="flex-center">
                      <PlatformIcon :data="scope.row[settingItem.fieldName]" />
                      {{ scope.row[settingItem.fieldName] || '--' }}
                    </div>
                  </template>
                  <template v-else-if="legalTableProps[settingItem.fieldName].showType === 'normal'">
                    <ToolTip :content="scope.row[settingItem.fieldName]" />
                  </template>
                  <template v-else-if="settingItem.fieldName === 'reviewProgress'">
                    <el-progress
                      v-if="handelProgess(scope.row[settingItem.fieldName]) || handelProgess(scope.row[settingItem.fieldName]) === 0"
                      :percentage="handelProgess(scope.row[settingItem.fieldName])"
                      :stroke-width="10"
                      :format="() => scope.row[settingItem.fieldName]"
                      :color="`${handelProgess(scope.row[settingItem.fieldName]) === 100 ? '#31CC9C' : '#406eff'}`"
                      class="progress-cell" />
                    <ToolTip v-else :content="scope.row[settingItem.fieldName]"/>
                  </template>
                  <template v-else-if="settingItem.fieldName === 'lastAuditTime'">
                    {{ scope.row.lastAuditTime/1000 | standardFormatNoHour('YYYY/MM/DD HH:mm', '--') }}
                  </template>
                  <template v-else-if="settingItem.fieldName === 'contractType'">
                    {{ scope.row.contractType | contractType }}
                  </template>
                  <template v-else-if="settingItem.fieldName === 'recycleAttachmentNum'">
                    <span v-if="canScanFileUpload(scope)" class="contract-recycle" @click="contractRecycle(scope)">
                      {{ scope.row.recycleAttachmentNum || '上传' }}
                      <span v-if="scope.row.recycleAttachmentNum"> 个</span>
                    </span>
                    <span v-else class="contract-recycle disable">
                      {{ scope.row.recycleAttachmentNum || '上传' }}
                      <span v-if="scope.row.recycleAttachmentNum"> 个</span>
                    </span>
                  </template>
                  <template v-else-if="settingItem.fieldName === 'creator'">
                    <ToolTip v-if="scope.row.creator" :content="`${scope.row.creator} ${scope.row.creatorPost || ''}`"/>
                    <span v-else>--</span>
                  </template>
                  <template v-else-if="settingItem.fieldName === 'proposer'">
                    <ToolTip v-if="scope.row.proposer" :content="`${scope.row.proposer} ${scope.row.post || ''}`"/>
                    <div v-else>--</div>
                  </template>
                  <template v-else-if="settingItem.fieldName === 'subjectName'">
                    <ToolTip :content="scope.row.subjectName" />
                  </template>
                  <template v-if="settingItem.fieldName === 'contractDate'">
                    {{ scope.row.contractDate | mapOptions(options.dateTypeOptions) }}
                  </template>
                  <template v-else-if="settingItem.fieldName === 'contractEffectEndDate'">
                    <el-tooltip :open-delay="800" placement="top" effect="dark">
                      <div slot="content" style="max-width: 220px; white-space: nowrap; padding: 0 10px;">
                        <span v-if="scope.row.contractDate === 1 || scope.row.contractDate === null">{{ scope.row.contractEffectStartDate/1000 | standardFormatNoHour('YYYY/MM/DD', '--') }} - {{ scope.row.contractEffectEndDate/1000 | standardFormatNoHour('YYYY/MM/DD', '--') }}</span>
                        <span v-else>{{ scope.row.pushTime/1000 | standardFormatNoHour('YYYY/MM/DD', '--') }}</span>
                      </div>
                      <div class="line-clamp1">
                        <span v-if="scope.row.contractDate === 1 || scope.row.contractDate === null">{{ scope.row.contractEffectStartDate/1000 | standardFormatNoHour('YYYY/MM/DD', '--') }} - {{ scope.row.contractEffectEndDate/1000 | standardFormatNoHour('YYYY/MM/DD', '--') }}</span>
                        <span v-else>{{ scope.row.pushTime/1000 | standardFormatNoHour('YYYY/MM/DD', '--') }}</span>
                      </div>
                    </el-tooltip>
                  </template>
                  <template v-else-if="settingItem.fieldName === 'createTime'">
                    {{ scope.row.createTime / 1000 | standardFormat('YYYY/MM/DD') }}
                  </template>
                </template>
              </u-table-column>
            </template>
            <u-table-column :width="operateWidth" align="left" label="操作" fixed="right">
              <template slot-scope="scope">
                <div style="display:flex;">
                  <div v-if="hasRouteAuth('crm:contract:read') && scope.row.process !== 0 && !showMobilePage" class="button-text" @click="toDetail(scope.row)">查看</div>
                  <MoreOpeator
                    :list="[
                      {label: '查看', handelClick: () => {toDetail(scope.row)}, auth: hasRouteAuth('crm:contract:read') && showMobilePage && scope.row.process !== 0},
                      {label: '复制', handelClick: () => {handlerCreateNew(scope.row)}, disabled: scope.row.process === 0 || !hasRouteAuth('crm:contract:add')},
                      {label: '编辑', handelClick: () => {toEdit(scope)}, disabled: setEditDisable(scope.row)},
                      {label: '删除', handelClick: () => {toDelete(scope)}, disabled: setDelDisable(scope.row)},
                      {label: '转交', handelClick: () => {handleSingleApproverChange(scope.row.id)}, disabled: setChangeDisable(scope.row)},
                    ]"
                  >
                    <div v-if="!showMobilePage" slot="button" :class="{'bl':hasRouteAuth('crm:contract:read') && scope.row.process !== 0}" class="button-text">更多<i class="el-icon-arrow-down"/></div>
                    <el-image v-else slot="button" :src="operateBtns" class="dropdown-img"/>
                  </MoreOpeator>
                </div>
              </template>
            </u-table-column>
          </u-table>
          <empty-placeholder v-else-if="!list.isInit" style="margin-bottom: 24px" />
        </div>
        <el-row v-if="showMobilePage" type="flex" justify="left">
          <el-pagination
            v-show="list.total > 0"
            :current-page="list.page"
            :page-size="list.perPage"
            :total="list.total"
            :small="true"
            :page-sizes="[20, 50, 100, 250, 500]"
            :layout="pageLayout"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </el-row>
        <fixed-pagination v-if="list.total > 0 && !showMobilePage || showMobilePage">
          <template v-if="showMobilePage">
            <FilterInput v-model="filterInput" :filter-list="filterList" show-mobile-icon show-search-btn class="FilterTool" @handelClick="queryClick" @queryEmpty="queryEmpty" @filterTagStatus="filterTagStatus" />
            <MoreOpeator
              ref="btnGroupRef"
              :list="moreOperatorList"
              show-mobile-icon
            />
            <el-button :class="{'mobile-btn':showMobilePage}" type="primary" size="small" class="empty-btn-style" @click="showContractTemplate">合同模板</el-button>
            <!-- <MoreOpeator
              v-if="hasRouteAuth('crm:contract:add')"
              :list="createOpeatorList"
              class="width-flex"
            >
              <createBtn slot="button" mobile-table style="width: 100%;flex:1;"/>
            </MoreOpeator> -->
            <createBtn v-if="hasRouteAuth('crm:contract:add')" style="margin-right: 10px;" @click.native="toCreate"/>
          </template>
          <template v-else>
            <SelectionNum :select-item="multipleSelectionAll" @clearMixinSelection="clearMixinSelection" />
            <span style="flex:1;"/>
            <el-pagination
              :current-page="list.page"
              :page-size="list.perPage"
              :total="list.total"
              :page-sizes="[20, 50, 100, 250, 500]"
              layout="total, prev, pager, next, sizes, jumper"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange" />
          </template>
        </fixed-pagination>
      </div>
    </div>
    <DiversAuditorDialog ref="auditorDialog" :can-empty="false" @handleSender="handleBatchSender" />
    <ContractRecycleDialog ref="contractRecycleDialog" @success="recycleSuccess" />
    <ApproverChange ref="approverChangeDialog" :business-type="BUSINESS_TYPE.CONTRACT" :ids="curSelectedId" @changeCallBack="changeCallBack"/>
    <ContractTemplate ref="contractTemplateRef" :is-fill="false" />
    <orderSetting ref="orderSetting" :setting-type="'contract'" :init-order-list="initLegalList" @handelSubmit="getTableSetting"/>
    <UploadDialog
      ref="uploadDialogRef"
      is-contract
      accept=""
      @uploadList="fetchData"
    />
  </div>
</template>

<script>
import setting from '@/assets/setting.png';
import createButton from '@/components/CreateButton';
import ImportButton from '@/components/ImportButton';
import ExportButton from '@/components/ExportButton';
import Title from '@/components/Title';
import ListTab from '@/components/ListTab';
import upAttachment from '@/components/Common/upAttachment/index';
import EmptyPlaceholder from '@/components/EmptyPlaceholder';
import ContractRecycleDialog from '@/components/contractRecycle/contractRecycleDialog';
import MoreOpeator from '@/components/Common/baseComponent/moreOpeator';
import DiversAuditorDialog from '@/components/Common/auditProcess/module/diversAuditorDialog';
import ApproverChange from '@/components/Common/auditProcess/approverChange';
import ContractTemplate from '@/components/legal/contractTemplate/index';
import createBtn from '@/components/Common/baseComponent/createBtn';
import PlatformIcon from '@/components/Common/platformIcon';
import UploadDialog from '@/views/order/model/uploadDialog';

import { getList, deleteContract, getContractListTabs } from '@/api/legal';
import { getOrderSetting } from '@/api/order';
import { getDepartmentAll } from '@/api/config';
import { getIssueOurTitleList } from '@/api/issueInvoice';
import { platformList } from '@/api/select';

import { standardFormatNoHour, standardFormat } from '@/filters/date';
import { contractType } from '@/filters/status';
import { mapOptions } from '@/filters';
import { hasRouteAuth } from '@/utils/permission';
import { encryption } from '@/utils';
import { BUSINESS_TYPE } from '@/utils/const/process';
import { paramsRangeFormat, paramsAryToStr } from '@/utils/paramsFormat';
import { PROCESS_TYPE } from '@/utils/const/process';
import options from './module/options';
import tableSelections from '@/mixins/tableSelections';
import filterObjStoreMixin from '@/mixins/filterObjStore';
import { mapState } from 'vuex';
import TableAdaptive from '@/mixins/tableAdaptive';
import mobileTable from '@/mixins/mobileTable';
import { initLegalList, legalTableProps } from './tableData';
import orderSetting from '@/components/OrderList/orderSetting';
import copyLink from '@/mixins/copyLink';
import schedule from '@/mixins/schedule';
import approverChange from '@/mixins/approverChange';
import axios from 'axios';
import { expeditedOptions } from '@/filters/status';
import { handelProgess } from '@/utils/process';

export default {
  name: 'ContractManagement',
  filters: {
    standardFormatNoHour,
    standardFormat,
    contractType,
    mapOptions
  },
  components: {
    orderSetting,
    createButton,
    ImportButton,
    ExportButton,
    Title,
    ListTab,
    EmptyPlaceholder,
    upAttachment,
    ContractRecycleDialog,
    MoreOpeator,
    ApproverChange,
    ContractTemplate,
    createBtn,
    DiversAuditorDialog,
    PlatformIcon,
    UploadDialog
  },
  mixins: [tableSelections, TableAdaptive, filterObjStoreMixin, mobileTable, copyLink, schedule, approverChange],
  data() {
    return {
      BUSINESS_TYPE,
      legalTableProps, initLegalList,
      setting,
      sortType: '',
      sortName: '',
      recycleStatusOption: [{
        value: 0,
        label: '未回收'
      }, {
        value: 1,
        label: '已回收'
      }],
      tabList: [],
      list: {
        items: [],
        page: 1,
        perPage: 20,
        total: 0,
        isInit: true
      },
      listLoading: true,
      handleStatus: -1,
      options,
      filterInput: {},
      deptTreeList: [],
      curSelectedId: '', // 请求变更操作的合同id
      ids: '', // 列表当前选中的id
      tableRefName: 'legalTableRef',
      idKey: 'id',
      isUmyTable: true,
      rangeKeyArr: [{
        attr: 'contractEffectStartDate',
        start: 'contractEffectStartDateStart',
        end: 'contractEffectStartDateEnd',
        type: 'time',
        addTime: true
      }, {
        attr: 'contractEffectEndDate',
        start: 'contractEffectEndDateStart',
        end: 'contractEffectEndDateEnd',
        type: 'time',
        addTime: true
      }, {
        attr: 'contractAmount',
        start: 'contractAmountMin',
        end: 'contractAmountMax',
        type: 'moneyFixedTwo'
      },
      { attr: 'createTime',
        start: 'createStartTime',
        end: 'createEndTime',
        type: 'time',
        addTime: true
      }],
      arrayKeyArr: ['departmentIdList'],
      tabCancelToken: null,
      cancelToken: null,
      tableSetting: [],
      subjectOptions: [],
      orderPlatformOption: []
    };
  },
  computed: {
    ...mapState({
      'userInfo': state => state.user.userInfo,
      'showMobilePage': state => state.app.showMobilePage
    }),
    filterList() {
      return [
        { keyword: 'contractName', name: '项目名称', type: 'input', labelWidth: '99px' },
        { keyword: 'contractCode', name: '合同编号', type: 'input', labelWidth: '99px' },
        { keyword: 'flowCode', name: '流程编码', type: 'input', labelWidth: '99px' },
        { keyword: 'pendApproval', name: '待审批人员', type: 'input', labelWidth: '99px' },
        { keyword: 'approver', name: '审批人', type: 'input', labelWidth: '99px' },
        { keyword: 'proposer', name: '申请人', type: 'input', labelWidth: '99px' },
        { keyword: 'creator', name: '创建人', type: 'input', labelWidth: '99px' },
        // { keyword: 'waitApprover', name: '待审批角色', type: 'input', labelWidth: '99px' },
        { keyword: 'oppCompany', name: '签约对方', type: 'input', labelWidth: '99px' },
        { keyword: 'archiveCode', name: '归档编号', type: 'input', labelWidth: '99px' },
        { keyword: 'comment', name: '评论', type: 'input', labelWidth: '99px' },
        { keyword: 'approvalComment', name: '审批意见', type: 'input', labelWidth: '99px' },
        { keyword: 'accountId', name: '账号ID', labelWidth: '100px', type: 'input' },
        { keyword: 'contractAmount', name: '合同金额', labelWidth: '99px', type: 'inputRange', isRequired: true, startPlaceholder: '最低金额', endPlaceholder: '最高金额', max: 999999999 },
        { keyword: 'contractType', name: '合同类型', type: 'select', options: [...options.typeOptions] },
        { keyword: 'tempSource', name: '合同模板来源', type: 'select', options: [...options.tempSourceOptions, { value: 4, label: '新拟定' }], placeholder: '模板来源' },
        { keyword: 'contractSubject', name: '我方签约主体', type: 'select', options: this.subjectOptions, placeholder: '签约主体' },
        { keyword: 'contractDate', name: '合作方式', type: 'select', options: [...options.dateTypeOptions] },
        { keyword: 'departmentIdList', name: '申请人部门', type: 'cascaderSelectWithChild', childrenVal: 'children', options: this.deptTreeList },
        { keyword: 'contractEffectStartDate', name: '合同起始日期', type: 'rangeDate', timeType: 'daterange', labelWidth: '99px', addQuickOptions: [30, 90] },
        { keyword: 'contractEffectEndDate', name: '合同结束日期', type: 'rangeDate', timeType: 'daterange', labelWidth: '99px', addQuickOptions: [30, 90] },
        { keyword: 'createTime', name: '创建时间', type: 'rangeDate', timeType: 'daterange', labelWidth: '99px' },
        { keyword: 'process', name: '审批状态', type: 'select', options: [...options.auditOptions] },
        {
          keyword: 'waitApprover',
          name: '待审批角色',
          type: 'loadMoreSelect',
          valueName: 'name',
          directShow: true,
          multiple: true,
          extendParams: { needNumber: 0 },
          labelName: 'name',
          placeholder: '待审批角色',
          searchkeyword: 'keyword',
          apiUrl: 'admin/contract/pendApproval/list' },
        { keyword: 'isExpedited', name: '是否加急', type: 'select', options: expeditedOptions },
        { keyword: 'rebates', name: '销售折扣/返利', type: 'select', options: [{ value: 1, label: '有' }, { value: 0, label: '无' }] },
        { keyword: 'platformId', name: '下单平台', type: 'select', options: this.orderPlatformOption }
      ];
    },
    moreOperatorList() {
      return [
        { label: '批量转交', handelClick: () => this.handleBatchApproverChange(this.BUSINESS_TYPE.CONTRACT) },
        { label: '自定义列', handelClick: this.tableSettingOpen },
        { label: '批量抄送', handelClick: this.handleSendMsg },
        { label: '复制链接', handelClick: this.batchCopyLink },
        { label: '批量合同回收', handelClick: this.uploadDialogShow, auth: this.hasRouteAuth('crm:contract:recycle') }
      ];
    }
    /* createOpeatorList() {
      const arr = [];
      this.options.typeOptions.forEach(i => {
        arr.push({
          label: i.label,
          tip: i.tip,
          delay: 800,
          handelClick: () => { this.toCreate(i.value); }
        });
      });
      return arr;
    } */
  },
  beforeRouteEnter(to, from, next) {
    if (from.name === 'EditContract' || from.name === 'CreateContract') {
      to.meta.isChange = false;
      // to.meta.handleStatus = 2;
    } else if (from.name === 'contractDetail') {
      to.meta.isChange = false;
    } else {
      to.meta.isChange = true;
    }
    next();
  },
  activated() {
    if (this.$route.query.oppCompany) {
      this.filterInput = this.$route.query;
    }
    if (this.$route.meta.handleStatus) {
      this.handleStatus = this.$route.meta.handleStatus;
    }
    const { isChange } = this.$route.meta;

    const { accountId, platformId } = this.$route.query;
    if (accountId && (platformId || platformId === 0)) {
      this.$set(this.filterInput, 'accountId', accountId);
      this.$set(this.filterInput, 'platformId', Number(platformId));
    }
    this.fetchData(!!isChange);
    this.queryDeptTreeList();
    this.getTableSetting();
    this.getSubJectOptions();
    this.platformList();
  },
  methods: {
    handelProgess,
    hasRouteAuth,
    getDetailLink(item) {
      if (!this.hasRouteAuth('crm:contract:read') || !item.process) return null;
      return `${location.origin}#/legal/contractDetail/${encryption(item.id)}?processId=${encryption(item.processId)}`;
    },
    // 获取下单平台的列表
    async platformList() {
      try {
        const result = await platformList();
        result.data.forEach((i) => {
          i.label = i.value;
          i.value = i.id;
        });
        this.orderPlatformOption = result.data;
      } catch (error) {
        console.log(error);
      }
    },
    getSubJectOptions() {
      this.subjectOptions = [];
      getIssueOurTitleList().then(res => {
        if (res.code === 200) {
          res.data.forEach(item => {
            this.subjectOptions.push({
              value: item.id,
              label: item.name,
              isStringVal: true,
              name: '所属公司'
            });
          });
        }
      });
    },
    sortMethod(a) {
      if (!a.order) {
        this.sortName = '';
        this.sortType = '';
      } else {
        this.sortName = a.prop;
        this.sortType = a.order === 'ascending' ? 1 : -1;
      }
      this.fetchData();
    },
    queryDeptTreeList() {
      getDepartmentAll().then(res => {
        this.deptTreeList = (res && res.data) || [];
      }).catch(e => {
        console.log(e);
      });
    },
    uploadDialogShow() {
      this.$refs['uploadDialogRef'].dialogShow();
    },
    // 审批人员单个合同变更
    handleSingleApproverChange(id) {
      if (!id) {
        this.$message.warning('合同ID无效');
        return;
      }
      this.curSelectedId = id + '';
      this.$refs['approverChangeDialog'].dialogVisible = true;
    },
    /*
      是否可以上传
      1、合同进程状态为审批中并且开启合同回收事件和拥有扫描件上传权限
      2、合同进程状态为已完成并且同时拥有扫描件上传权限和扫描件查看/下载权限
    */
    canScanFileUpload(scope) {
      const processStatus = scope.row.process;
      const setEvents = scope.row.setEvents;
      if (processStatus === 1) {
        return setEvents && setEvents.includes(1) && this.hasRouteAuth('crm:contract:scanFileUpload');
      } else if (processStatus === 4) {
        return this.hasRouteAuth('crm:contract:scanFileUpload') && this.hasRouteAuth('crm:contract:scanFileDownload');
      }
      return false;
    },
    contractRecycle(scope) {
      this.$refs['contractRecycleDialog'].dialogVisible = true;
      const data = {
        id: scope.row.id,
        attachment: scope.row.recycleAttachment || [],
        isReview: scope.row.process === 4 && hasRouteAuth('crm:contract:scanFileDownload') || (scope.row.process === 1 && hasRouteAuth('crm:contract:scanFileDownload') && scope.row.setEvents && scope.row.setEvents.includes(1))
      };
      this.$refs['contractRecycleDialog'].initInfo(data);
    },
    setEditDisable(data) {
      return !(this.hasRouteAuth('crm:contract:edit') && data.process === 0 && data.creatorId === this.userInfo.id);
    },
    setDelDisable(data) {
      // 草稿中、未过审、已作废和待提交状态允许删除合同
      return !([0, 2, 3, 5].includes(data.process) && (this.hasRouteAuth('crm:contract:delete') || data.creatorId === this.userInfo.id));
    },
    setChangeDisable(data) {
      return !(hasRouteAuth('crm:contract:approverChange') && ![0, 4].includes(data.process));
    },
    recycleSuccess() {
      this.fetchData();
    },
    handleTabClick(id) {
      this.handleStatus = id;
      this.queryClick();
    },
    // 多选
    tableSelectionChange(e) {
      this.selectList = e;
      this.ids = e.map(item => item.id).join(',');
    },
    queryClick() {
      this.fetchData(true);
    },
    queryEmpty() {
      this.sortType = '';
      this.sortName = '';
      this.filterInput = {};
      this.queryClick();
    },
    importCallback() {
      this.fetchData(true);
    },
    formatParams() {
      const params = JSON.parse(JSON.stringify(this.filterInput));
      paramsRangeFormat(this.rangeKeyArr, params);
      paramsAryToStr(this.arrayKeyArr, params);
      params.page = this.list.page;
      params.perPage = this.list.perPage;
      params.handleStatus = this.handleStatus;
      params.sortName = this.sortName;
      params.sortType = this.sortType;
      if (params.waitApprover && params.waitApprover.length) {
        params.waitApprover = `,${params.waitApprover.join(',')},`;
      }
      return params;
    },
    async getTabList() {
      try {
        const params = this.formatParams();
        if (this.tabCancelToken) this.tabCancelToken.cancel('cancel');
        const source = axios.CancelToken.source();
        this.tabCancelToken = source;
        const result = await getContractListTabs(params, source.token);
        if (result.code === 200) {
          // result.data.unshift({ name: '全部', id: -1 });
          this.tabList = result.data;
          // this.handleStatus = result.data[0].id;
        }
      } catch (error) {
        this.tabList = [
          { id: 0, name: '待处理', num: 0 },
          { id: 1, name: '已处理', num: 0 },
          { id: 2, name: '我发起的', num: 0 },
          { id: 3, name: '我收到的', num: 0 }
        ];
        console.log(error);
      }
    },
    // 表格tab切换按钮
    statusTabChange(status) {
      this.handleStatus = status;
      this.queryClick();
    },
    fetchData(reset = false) {
      try {
        if (reset) this.list.page = 1;
        this.listLoading = true;
        const params = this.formatParams();
        if (this.cancelToken) this.cancelToken.cancel('cancel');
        const source = axios.CancelToken.source();
        this.cancelToken = source;
        this.getTabList();
        getList(params, source.token).then(({ data }) => {
          this.list = data;
          this.list.isInit = false;
          this.listLoading = false;
          this.setSelectRow && this.setSelectRow(data.items);
          if (this.$refs.legalTableRef && this.$refs.legalTableRef.$el) {
            const tagleScrollEl = this.$refs.legalTableRef.$el.querySelector('.is-scrolling-left');
            if (tagleScrollEl) tagleScrollEl.scrollTop = 0;
          }
        }, result => {
          this.listLoading = false;
          this.list.isInit = false;
        }).catch(e => {
          console.error(e);
        });
      } catch (error) {
        console.log(error);
      }
    },
    toEdit(scope) {
      this.$router.push({
        name: 'EditContract',
        params: {
          id: encryption(scope.row.id)
        }
      });
    },
    toCreate() {
      /* this.$router.push({
        name: 'CreateContract',
        query: {
          type
        }
      }); */
      this.$router.push({ name: 'CreateContract' });
    },
    toDetail(row) {
      this.filterObjStore(PROCESS_TYPE.CONTRACT);
      this.$router.push({
        name: 'contractDetail',
        params: { id: encryption(row.id) },
        query: {
          processId: encryption(row.processId),
          fromList: 1
        }
      });
    },
    async toDelete(scope) {
      this.$confirm('确定删除该合同？', '', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        center: true,
        type: 'warning',
        customClass: 'del-message del-message-cancel',
        iconClass: 'del-icon'
      }).then(() => {
        deleteContract(scope.row.id).then(res => {
          this.$message.success('删除成功');
          if (this.list.page > 1 && this.list.perPage * (this.list.page - 1) + 1 === this.list.total) {
            this.list.page--;
          }
          this.resetItemSelected(scope.row.id);
          this.fetchData();
        }, result => {
          // this.$message.error(result.message);
        }).catch(err => {
          console.error(err);
        });
      });
    },
    handleSizeChange(val) {
      this.list.perPage = val;
      this.fetchData(true);
    },
    handleCurrentChange(toPage) {
      this.list.page = toPage;
      this.fetchData();
    },
    showContractTemplate() {
      this.$refs['contractTemplateRef'].dialogVisible = true;
    },
    getTableSetting() {
      getOrderSetting().then((res) => {
        let tableSetting = [];
        this.tableSetting = [];
        if (res.code === 200 && res.data && res.data.contract) {
          tableSetting = this.jsonParse(res.data.contract);
        } else {
          tableSetting = JSON.parse(JSON.stringify(initLegalList));
        }
        this.$nextTick(() => {
          this.tableSetting = tableSetting;
          this.$forceUpdate();
        });
      });
    },
    tableSettingOpen() {
      this.$refs.orderSetting.openDialog(this.tableSetting);
    },
    jsonParse(str) {
      if (typeof str !== 'string') return str;
      try {
        const list = JSON.parse(str);
        return list && list.length > 0 ? list : JSON.parse(JSON.stringify(initLegalList));
      } catch (error) {
        return JSON.parse(JSON.stringify(initLegalList));
      }
    },
    handlerCreateNew(row) { // 再次发起（复制）
      const routeUrl = this.$router.resolve({
        name: 'EditContract',
        params: {
          id: encryption(row.id)
        },
        query: {
          createNew: 1,
          reapply: row.processId
        }
      });
      window.open(routeUrl.href, '_blank');
    }
  }
};
</script>
<style rel="stylesheet/scss" lang="scss" scoped>
.customer {
  .table-list {
    margin: 16px 16px 0 16px;
    background-color: #fff;
    padding: 20px 20px 55px 20px;
    .el-row {
      padding: 0;
    }
    .empty-btn-style {
      border-color: #406EFF;
      background: #fff;
      color: #406EFF;
      padding: 7px 14px;
      text-align: center;
      margin-right: 10px;
      &:hover {
        background: #406EFF;
        color: #fff;
      }
    }
  }
}
.contract-recycle {
  cursor: pointer;
  color: #406EFF;
  font-weight: bold;
  &.disable {
    cursor: not-allowed;
    color: #999999;
  }
}
.mobile-btn {
  height: 36px;
  font-size: 16px;
}
.batch-set {
  display: flex;
  align-items: center;
  padding: 0 12px;
  font-size: 14px;
  background: #406eff;
  border-color: #406eff;
  color: #fff;
  height: 32px;
}
.width-flex {
  flex:1;
  &::v-deep {
    .el-dropdown {
      width: 100%;
    }
  }
}
</style>
<style lang="scss">
.mobile-table {
  & td {
    height: 40px !important;
  }
}
</style>

